<template>
  <div>
    <a-table
      ref="tableList"
      @mouseleave.native="onMouseLeaveTable"
      :columns="columns"
      :data-source="dataSource"
      :rowSelection="{ selectedRowKeys: this.selectedRowKeys, onChange: this.onSelectChange }"
      :row-key="(record) => record.id"
      :pagination="{
        total: this.totalCount,
        showSizeChanger: true,
        onChange: this.tablePageChange,
        onShowSizeChange: this.paginationSizeChange,
      }"
      :loading="loading"
      :customRow="
        (record, index) => {
          return {
            on: {
              mouseenter: (e) => {
                this.currentRowId = record.id
              },
            },
          }
        }
      "
    >
      <!-- 封面图  -->
      <template slot="cover_pic" slot-scope="text">
        <div class="goods-info">
          <img class="goods-pic" :src="text" alt="" />
        </div>
      </template>
      <!-- 设备名称 -->
      <template slot="name" slot-scope="text">
        <div class="goods-info">
            <div style="font-weight: bold; line-height: 25px; " class="of_el">
              {{ text }}
            </div>
        </div>
      </template>
      <!-- 序列号 -->
      <template slot="serial" slot-scope="text">
        <div class="goods-price-row">
          <span>{{ text }}</span>
        </div>
      </template>
      <!-- 验证码 -->
      <template slot="code" slot-scope="text">
        <div class="goods-rest-row">
          <span>{{ text }}</span>
        </div>
      </template>
      <!-- 上下架 -->
      <template slot="status" slot-scope="text">
        <div class="goods-rest-row">
          <span>{{ text == 1 ? "在线" : "掉线" }}</span>
        </div>
      </template>
      
      <!-- 操作 -->
      <span class="table-action" slot="action" slot-scope="text, item">
        <a @click="edit(item)">编辑</a>
        <a-divider type="vertical" />
        <a @click="del(item.id)">解除绑定</a>
      </span>
    </a-table>

    <!-- 编辑规格弹框 -->
    <EditAttrModal
      :visible="isShowEditAttrModal"
      :currentGood="currentGood"
      @onAfterClose="onAfterClose"
      @onHandleOk="onAfterClose"
    ></EditAttrModal>
  </div>
</template>

<script>
import { list,delDeviceItem  } from '@/api/adopt/device'
// import EditAttrModal from './EditAttrModal'
// import MyPopover from './MyPopover'

const columns = [
  {
    title: '设备ID',
    dataIndex: 'id',
    key: 'id',
  },
  {
    title: '封面图',
    dataIndex: 'cover_pic',
    key: 'cover_pic',
    scopedSlots: { customRender: 'cover_pic' },
  },
  {
    title: '设备名称',
    dataIndex: 'name',
    key: 'name',
    scopedSlots: { customRender: 'name' },
  },
  {
    title: '序列号',
    dataIndex: 'serial',
    key: 'serial',
    defaultSortOrder: '',
    scopedSlots: { customRender: 'serial' },
  },
  {
    title: '验证码',
    dataIndex: 'code',
    key: 'code',
    defaultSortOrder: '',
    scopedSlots: { customRender: 'code' },
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    scopedSlots: { customRender: 'status' },
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' },
  },
]

const attrColumns = [
  {
    title: '规格',
    dataIndex: 'attr_list',
    width: 200,
    scopedSlots: { customRender: 'attr_list' },
  },
  {
    title: '库存',
    dataIndex: 'num',
    width: 80,
    scopedSlots: {
      filterDropdown: 'numDropdown',
      filterIcon: 'numIcon',
      customRender: 'num',
    },
  },
  {
    title: '价格',
    dataIndex: 'price',
    width: 80,
    scopedSlots: {
      filterDropdown: 'priceDropdown',
      filterIcon: 'priceIcon',
      customRender: 'price',
    },
  },
]

export default {
  components: {
    // MyPopover,
    // EditAttrModal,
  },
  props: {
    status: {
      type: Number,
      default: -1,
    },
    // queryParam: {
    //   type: Object,
    //   default: () => {
    //     return {
    //       name: '',
    //       cat_id: 0,
    //       status: -1,
    //       mch_id: 0,
    //     }
    //   },
    // },
  },
  data() {
    return {
      isShowEditAttrModal: false,
      currentRowId: '',
      goodsId: '',
      columns: columns,
      selectedRowKeys: [],
      goods_id: 0,
      attr: [],
      visible: false,
      attrColumns: attrColumns,
      autoFocusData: { type: '', index: 0 }, // 获取焦点参数
      updateParams: {
        name: '',
        price: null,
        virtual_sales: null,
        goods_num: null,
      },
      isShowSaleConfDrawer: false,
      currentGood: {},
      dataSource: [],
      totalCount: 0,
      pageSize: 10,
      pageNo: 1,
      showNamePopover: false,
      showPricePopover: false,
      showRestPopover: false,
      showVirtualPopover: false,
      currentGoodsItem: {},
      pagination: {},
      loading: false,
      showQrCode: false,
      qrcodeUrl: '',
    }
  },
  created() {},
  mounted() {
    this.getDeviceData()
  },
  methods: {
    // 获取设备列表数据
    getDeviceData() {
      var newObj = {}
      newObj = {  status: this.status, pageNo: this.pageNo, pageSize: this.pageSize }
      this.loading = true
      return list(newObj).then((res) => {
        this.loading = false
        if (!res.code) {
          this.dataSource = res.data.data
          this.totalCount = res.data.totalCount
        }
      })
    },
    // 分页请求
    tablePageChange(e) {
      console.log(e)
      this.pageNo = e
      this.getDeviceData()
    },
    // 分页器页数修改回调
    paginationSizeChange(current, size) {
      console.log(current, size)
      this.pageNo = current
      this.pageSize = size
      this.getDeviceData()
    },
    // 编辑 调用父组件方法
    edit(item){
      console.log("这时候再子组件");
      this.$emit("handleEdit",item);
    },
    del(item){
      var newObj = {}
      newObj = { device_id: item}
      console.log(newObj);
      this.loading = true
      return delDeviceItem(newObj).then((res) => {
        this.loading = false
        if (!res.code) {
          this.dataSource = res.data.data
          this.totalCount = res.data.totalCount
        }
      })
    },
    

    
  
    // 点击修改，弹出Popover
    openPopover(row, index) {
      console.log(row, index)
      this.currentGoodsItem = row
      this.updateParams.name = row.name
      this.updateParams.price = parseFloat(row.price)
      this.updateParams.virtual_sales = Number(row.virtual_sales)
      this.updateParams.goods_num = Number(row.goods_num)
      if (index == 0) {
        this.showNamePopover = true
        return
      }
      if (index == 1) {
        this.showPricePopover = true
        return
      }
      if (index == 2) {
        this.showRestPopover = true
        return
      }
      if (index == 4) {
        this.showVirtualPopover = true
        return
      }
    },
    // 更新编辑的属性
    submitUpdate(row, index) {
      if (!this.updateParams.name) {
        this.$message.warn('商品名称不能为空')
        return
      }
      const params = {
        id: row.id,
        type: '',
        value: '',
      }
      switch (index) {
        case 0:
          params.type = 'name'
          params.value = this.updateParams.name
          break
        case 1:
          params.type = 'price'
          params.value = this.updateParams.price
          break
        case 2:
          params.type = 'goods_num'
          params.value = this.updateParams.goods_num
          break
        case 4:
          params.type = 'virtual_sales'
          params.value = this.updateParams.virtual_sales
          break
        default:
          break
      }
      this.resetPopover()
      setAttr(params).then((res) => {
        if (res.code === 0) {
          this.getDeviceData()
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    // 点击编辑属性
    setAttr(goodsId, attr, goods, index) {
      console.log(goods)
      this.currentGoodsItem = goods
      this.attr = JSON.parse(attr)
      this.goods_id = goodsId
      if (goods.use_attr == 1) {
        this.resetPopover()
        this.editAttr(goods)
      } else {
        this.openPopover(goods, index)
      }
    },
    // 修改规格回调
    onAfterClose(type) {
      this.isShowEditAttrModal = false
      this.currentGood = {}
      if (type) {
        this.getDeviceData()
      }
    },
    // 编辑规格
    editAttr(goods) {
      this.currentGood = goods
      this.isShowEditAttrModal = true
    },

    onMouseLeaveTable(e) {
      if (e.relatedTarget && e.relatedTarget.className.indexOf('popover') != -1) {
        return
      }
      this.currentRowId = ''
    },
    // 满减设置
    openDrawer(id, goods) {
      this.currentGood = goods
      this.goodsId = id
      this.isShowSaleConfDrawer = true
    },
    // 复制小程序链接
    copyUrl(id) {
      this.$copyText(`goods/goods/goods?id=${id}`).then(
        () => {
          this.$message.success('复制成功！')
        },
        () => {
          this.$message.error('复制成功！')
        }
      )
    },
    // 小程序二维码
    showQscode(id) {
      const h = this.$createElement
      this.$message.loading({ content: '请求中...', key: 'qrcodeLoading' })
      getQr({
        id,
      })
        .then((res) => {
          if (res.code === 0) {
            console.log(res)
            const qrcodeUrl = res.data.qr_url
            // this.$info({
            //   title: '小程序二维码',
            //   content: h('img', {
            //     attrs: {
            //       src: qrcodeUrl,
            //     },
            //     style: {
            //       width: '100%',
            //       margin: '10px auto',
            //     },
            //   }),
            // })
            this.showQrCode = true
            this.qrcodeUrl = qrcodeUrl
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch((error) => {
          console.log(error)
        })
        .then(() => {
          this.$message.destroy()
        })
    },
    // 刷新数据
    refresh() {
      this.getDeviceData()
    },
    // 操作编辑
    onEdit(id) {
    
      if (id > 0) {
        this.$router.push({ name: 'AdoptEdit', query: { id: id } })
      } else {
        this.$router.push({ name: 'AdoptAdd' })
      }
    },
    // 表格选中
    onSelectChange(selectedRowKeys) {
      console.log('selectedRowKeys changed: ', selectedRowKeys)
      this.selectedRowKeys = selectedRowKeys
    },
    // 删除数据
    delGoodById(id) {
      this.$confirm({
        title: '是否删除该条数据?',
        onOk: () => {
          updateAllApi({
            type: 'is_delete',
            status: 1,
            goods_id: [id],
          }).then((res) => {
            if (res.code === 0) {
              this.getDeviceData()
            } else {
              this.$message.error(res.msg)
            }
          })
        },
        onCancel() {},
      })
    },
    // 批量操作
    updateAll(type, status) {
      if (!this.selectedRowKeys.length) {
        this.$message.warn('请先勾选商品')
        return
      }
      var text = '删除'
      if (type === 'status') {
        text = status === 1 ? '上架' : '下架'
      } else if (type === 'quick_purchase') {
        text = status === 1 ? '加入快速购买' : '关闭快速购买'
      }
      this.$confirm({
        title: '是否批量' + text + '?',
        onOk: () => {
          updateAllApi({
            type: type,
            status: status,
            goods_id: this.selectedRowKeys,
          }).then((res) => {
            if (res.code === 0) {
              this.refresh()
            } else {
              this.$message.error(res.msg)
            }
          })
        },
        onCancel() {},
      })
    },

    updateParam(value, type) {
      console.log(value)
      this.queryParam[type] = value
    },

    handleOk() {
      this.$message.loading({ content: '提交中', key: 'loading' })
      setAttrNum({
        attr: this.attr,
        id: this.goods_id,
      }).then((res) => {
        if (res.code === 0) {
          this.visible = false
          this.refresh()
          this.$message.success({ content: res.msg, key: 'loading' })
        } else {
          this.$message.error({ content: res.msg, key: 'loading' })
        }
        this.resetPopover()
      })
    },
    /**
     * 修改规格数据
     */
    handleChange(value, type, index) {
      this.autoFocusData = {
        type: type,
        index: index,
      }
      this.attr[index][type] = value === null ? '' : value
    },
    settingAll(e, setSelectedKeys, selectedKeys) {
      this.attr.forEach((element, index) => {
        this.attr[index][setSelectedKeys.column.dataIndex] = e
      })
    },
  },
}
</script>
<style lang="less" scoped>
/deep/.ant-table-body {
  min-height: 360px;
}
.slotTable {
  /deep/.ant-table-row-cell-break-word {
    padding: 2px 8px !important;
  }
  /deep/.ant-table-body {
    min-height: 0px;
  }
}

/deep/.ant-table-body::-webkit-scrollbar {
  display: none; /*ChromeSafari*/
}

.of_el {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.table_operator_icon {
  font-size: 18px;
  padding: 0 5px;
  color: rgb(182, 182, 182);
  cursor: pointer;
  &:hover {
    color: rgb(24, 144, 255);
  }
}

.goods-info {
  display: flex;
  align-items: flex-start;
  position: relative;
  .goods-pic {
    width: 48px;
    height: 48px;
    border-radius: 4px;
    display: block;
  }
  .info-box {
    margin-left: 24px;
    margin-right: 5px;
    .goods-name {
      width: 185px;
      font-size: 14px;
      line-height: 22px;
      color: rgba(0, 0, 0, 0.65);
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
    }
  }
  .item-edit-box {
    width: 15px;
    height: 100%;
    position: absolute;
    right: -12px;
    top: 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
  }
}
.goods-price-row {
  position: relative;
  display: inline-block;
  .row-price-edit {
    position: absolute;
    right: -27px;
    top: 0;
    width: 15px;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

.goods-rest-row {
  position: relative;
  display: inline-block;
  .row-rest-edit {
    position: absolute;
    right: -27px;
    top: 0;
    width: 15px;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

.goods-virtual-row {
  position: relative;
  display: inline-block;
  .row-virtual-edit {
    position: absolute;
    right: -27px;
    top: 0;
    width: 15px;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

.goods-type {
  min-width: 60px;
  display: inline-block;
}
.table-action {
  min-width: 93px;
  display: inline-block;
}
</style>
